<script setup lang="ts">
import { ref,watch,onMounted , nextTick } from "vue";

const currentActive = ref(0)

const tabs = ref()

interface Props{
    active?:(number|string)
    tabs:string[]
}
const props = withDefaults(defineProps<Props>(), {
    active:0,
    tabs:<any>[]
})

const click = (e:any)=>{
    currentActive.value = e.target.getAttribute('data-index')
    updateUnderline();
    emit("change",currentActive.value);
}
const itemRefs = ref([]);
const underlineRef = ref(null);
const underlineStyle = ref({
  transform: "translateX(0)",
  display:'none'
});
async function updateUnderline(){
    await nextTick()

    if(itemRefs.value.length<0){
        return
    }
    const ref:any = itemRefs.value[currentActive.value] ?? itemRefs.value[0]
    let width = ref.offsetWidth
    let left = ref.offsetLeft + width/2 - 8
    underlineStyle.value = {
      transform: `translateX(${left}px)`,
      display:currentActive.value == -1?'none':'block'
    };

};

const emit = defineEmits<{
  change: [active: number]
}>()

watch(
    ()=>props.active,(newval,_oldval)=>{
        currentActive.value = Number(newval)
    }
)
watch(
    ()=>props.tabs,(newval,_oldval)=>{
        if(newval.length>0){
            tabs.value = newval
            currentActive.value = props.tabs.findIndex(function(item:any){
                return item.active === true
            })??0
            updateUnderline();
        }else{
            tabs.value = []
        }
    }
)

onMounted(() => {
    if(props.tabs.length>0){
        tabs.value = props.tabs
        currentActive.value = props.tabs.findIndex(function(item:any){
            return item.active === true
        })??0
        updateUnderline();
    }
});

</script>

<template>
    <div class="tabs" @click="click($event)">
        <div class="tabs_item" :class="currentActive == index ? 'active':'' " :data-index="index" v-for="(item,index) in tabs" ref="itemRefs">
            {{item.title}}
            <SvgIcon v-if="item.suffix" class="icon" :iconSize="1" :name="item.suffix"/>
        </div>
        <div ref="underlineRef" :style="underlineStyle" class="underline"></div>
    </div>
</template>

<style scoped>
    .tabs{display: flex; flex-wrap: nowrap; height:2.8rem;line-height:2.8rem; overflow-x:scroll; position: relative;}
    .tabs::-webkit-scrollbar{
        display:none;
    }
    .tabs_item{ font-size: 1rem; padding-right:2.5rem; cursor:pointer; transition:all 0.3s; font-size: 1.125rem;color:var(--color-text-t4);}
    .tabs_item.active{ color:var(--dy-theme-color); }
    .tabs_item:hover{ color:var(--dy-theme-color); }
    .tabs .underline{ position:absolute; top:2.6rem; left:0;width:1.2rem;height:3px; display:none; border-radius: 0.2rem; background-color:var(--dy-theme-color); transform: translateX(0rem); transition:all 0.3s; }
</style>